import java.io.IOException;
import java.net.URL;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import productidentification.IProductIdentifier;

public class Ian_ProductIdentifier_Plugin implements IProductIdentifier
{
	private static final int timeoutMillis = 3000;

	private String description;
	private String URL;

	public Ian_ProductIdentifier_Plugin()
	{
		URL = "http://www.upcdatabase.com/item/";
		description = "";
	}

	@Override
	public String identifyProduct(String barcode) throws Exception {
		String searchURL = URL + barcode;

		try
		{
			URL pageURL = new URL(searchURL);

			Document doc = Jsoup.parse(pageURL, timeoutMillis);
			Element table = doc.select(".data").first();
			if(table == null)
			{
				return "";
			}

			Elements descriptionElement = table.select(":containsOwn(Description)");
			description = descriptionElement.first().nextElementSibling().nextElementSibling().ownText();

			return description;
		}
		catch (NullPointerException e)
		{
			return "";
		}
		catch (IOException e)
		{
			System.out.println("Time out");
			return "";
		}
	}

	@Override
	public String getName() {
		return "Ian Ryu Product barcode identifier plugin";
	}

	@Override
	public String getDescription() {
		return "Using http://www.upcdatabase.com/item/" ;
	}

	public static void main(String[] args) throws Exception
	{
		String[] barcodes = {"035000509000", "300650192057"};
		Ian_ProductIdentifier_Plugin plugin = new Ian_ProductIdentifier_Plugin();

		for(String barcode : barcodes)
		{
			String tmp = plugin.identifyProduct(barcode);

			if(tmp.isEmpty())
			{
				System.out.println(barcode + ": this barcode has error.");
			}
			else
			{
				System.out.println("Barcode - " + barcode + " Description: "+ tmp);
			}

		}
	}

}
